/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.editors;

import cn.easyplatform.entities.BaseEntity;
import cn.easyplatform.entities.helper.EventLogic;
import cn.easyplatform.lang.Mirror;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.web.editors.entity.TaskEntityEditor;
import org.zkoss.zk.ui.Page;
import org.zkoss.zul.Button;
import org.zkoss.zul.Label;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class EventLogicCallback implements EditorCallback<String>,Tablable {

    private Editor editor;

    private Button btn;

    private EventLogic el;

    private String table;

    private String method;

    /**
     * @param editor
     * @param btn
     * @param el
     * @param method
     */
    public EventLogicCallback(Editor editor, Button btn,
                              EventLogic el, String table, String method) {
        this.editor = editor;
        this.btn = btn;
        this.el = el;
        this.table = table;
        this.method = "set" + method;
    }

    @Override
    public String getValue() {
        if (el.getContent() == null)
            return "";
        return el.getContent();
    }

    @Override
    public void setValue(String value) {
        if (Strings.isBlank(value)) {
            BaseEntity entity = ((AbstractEntityEditor<?>) editor).entity;
            Mirror<?> me = Mirror.me(entity.getClass());
            me.invoke(entity, method, (EventLogic) null);
            btn.setSclass("epeditor-btn");
        } else {
            btn.setSclass("epeditor-btn-mark");
            el.setContent(value);
        }
        ((AbstractEntityEditor<?>) editor).setDirty();
        if (editor instanceof TaskEntityEditor)
            ((AbstractEntityEditor<?>) editor).redraw();
    }

    @Override
    public String getTitle() {
        Label label = (Label) btn.getParent().getParent().getFirstChild();
        return label.getValue();
    }

    @Override
    public Page getPage() {
        return btn.getPage();
    }

    @Override
    public Editor getEditor() {
        return editor;
    }

    public String getTable() {
        return table;
    }
}
